package system

import (
	"fmt"
	"project-info/src/handle/common"
	"project-info/src/handle/response"
	"project-info/src/lib"
	"project-info/src/model"
	"strconv"

	"gorm.io/gorm"
)

type PageRoleReq struct {
	Search string `json:"search"`
	common.PageRequest
}

type GetRoleListReq struct {
	SearchName string `json:"searchName"`
	common.PageRequest
}

type RoleRes struct {
	RoleId   uint64 `json:"roleId"`
	RoleName string `json:"roleName"`
	Describe string `json:"describe"`
}

type GetRoleListRes struct {
	List []RoleRes `json:"list"`
}

func PageRole(c *lib.GinContext) error {
	var pageRoleReq *PageRoleReq
	if err := c.Bind(&pageRoleReq); err != nil {
		c.Logger().Error(err.Error())
		return response.JsonFail(c, "参数解析错误")
	}

	start, end := lib.Paging(pageRoleReq.Page, pageRoleReq.Size)

	var roles []model.Role
	var total int64

	db := model.DB().Model(&model.Role{})
	if pageRoleReq.Search != "" {
		db.Where("role_name like ?", fmt.Sprintf("%%%s%%", pageRoleReq.Search))
	}
	db.Count(&total).Order("id desc").Offset(start).Limit(end).Find(&roles)
	return response.JsonOk(c, map[string]interface{}{"records": roles, "total": total}, "")
}

func AddOrUpdateRole(c *lib.GinContext) error {
	var role model.Role
	if err := c.Bind(&role); err != nil {
		c.Logger().Error(err.Error())
		return response.JsonFail(c, "参数解析错误")
	}

	var err error
	if role.IsCreate() {
		err = model.DB().Create(&role).Error
	} else {
		err = model.DB().Save(&role).Error
	}

	if err != nil {
		c.Logger().Error(err.Error())
		return response.JsonFail(c, "保存失败")
	}
	return response.JsonOk(c, role, "操作成功")
}

// DeleteRole 删除角色
func DeleteRole(c *lib.GinContext) error {
	idString := c.QueryParam("id")
	// string id 转换为uint64
	id, err := strconv.ParseUint(idString, 10, 64)
	if err != nil {
		c.Logger().Error(err.Error())
		return response.JsonFail(c, "参数解析错误")
	}
	// 验证是否有关联用户
	var count int64
	model.DB().Model(&model.RoleUser{}).Where("role_id = ?", id).Count(&count)
	if count > 0 {
		return response.JsonFail(c, "该角色下关联有用户，无法删除")
	}

	model.DB().Model(&model.MenuRole{}).Where("role_id = ?", id).Count(&count)
	if count > 0 {
		return response.JsonFail(c, "该角色下关联有菜单，无法删除")
	}

	if err := model.DB().Delete(&model.Role{}, "id = ?", id).Error; err != nil {
		c.Logger().Error(err.Error())
		return response.JsonFail(c, "删除失败")
	}
	return response.JsonOk(c, nil, "删除成功")
}

// ListRole 获取角色列表
func ListRole(c *lib.GinContext) error {
	var roles []model.Role
	err := model.DB().Find(&roles).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		c.Logger().Error(err.Error())
		return response.JsonFail(c, "查询失败")
	}
	return response.JsonOk(c, roles, "查询成功")
}

// GetRoleList 获取角色列表（POST请求）
func GetRoleList(c *lib.GinContext) error {
	var req GetRoleListReq
	if err := c.Bind(&req); err != nil {
		c.Logger().Error(err.Error())
		return response.JsonFail(c, "参数解析错误")
	}

	var roles []model.Role
	db := model.DB().Model(&model.Role{})
	if req.SearchName != "" {
		db.Where("role_name like ?", fmt.Sprintf("%%%s%%", req.SearchName))
	}
	db.Find(&roles)

	var res GetRoleListRes
	for _, role := range roles {
		res.List = append(res.List, RoleRes{
			RoleId:   role.Id,
			RoleName: role.RoleName,
			Describe: role.Describe,
		})
	}

	return response.JsonOk(c, res, "查询成功")
}

// GetRoleOptions 获取用户选项
func GetRoleOptions(c *lib.GinContext) error {
	var roles []model.Role
	err := model.DB().Model(&model.Role{}).Select("id,role_name").Find(&roles).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		c.Logger().Error(err.Error())
		return response.JsonFail(c, "查询失败")
	}

	var options []common.OptionRes
	for _, role := range roles {
		options = append(options, common.OptionRes{Label: role.RoleName, Value: role.Id})
	}

	return response.JsonOk(c, options, "查询成功")
}
